package br.com.management.mentor.app.listeners.persisters;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Date;

import javax.persistence.EntityManager;

import org.springframework.beans.factory.annotation.Autowired;

import br.com.management.mentor.app.Config;
import br.com.management.mentor.model.entities.view.Menu;
import br.com.management.mentor.model.repositories.MenusRepository;
import br.com.management.mentor.model.repositories.PermissionsRepository;

import com.google.gson.reflect.TypeToken;

public class MenusEntityPersister implements EntityPersister<Menu> {

	@Autowired
	private MenusRepository menusRepository;

	@Autowired
	private PermissionsRepository permissionsRepository;

	@Override
	public void persist( EntityManager em , Collection<Menu> entities ) {
		for ( Menu menu : entities ) {
			if ( menusRepository.getByKey( menu.getKey() ) == null ) {
				menu.setCreationDate( new Date() );
				if ( menu.getPermission() != null )
					menu.setPermission( permissionsRepository.getByName( menu.getPermission().getName() ) );

				em.persist( menu );
			}
		}
	}

	@Override
	public Config getResourcePath() {
		return Config.MENUS_SOURCE_FILE;
	}
	
	@Override
	public Type getEntityType() {
		return new TypeToken<Collection<Menu>>() {}.getType();
	}

}